package com.tomorrow.payments_hodgepodge.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author Tomorrow
 * @date 2020/11/10 17:27
 */
public class ARBUtil {
    public static String AES_IV = "PGKEYENCDECIVSPC";

    public static String encryptAES(String key, String encryptString) {
        byte[] encryptedText = null;
        IvParameterSpec ivspec = null;
        SecretKeySpec skeySpec = null;
        Cipher cipher = null;
        byte[] text = null;
        String s = null;
        try {
            ivspec = new IvParameterSpec(AES_IV.getBytes("UTF-8"));
            skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
            text = encryptString.getBytes("UTF-8");
            encryptedText = cipher.doFinal(text);
            s = byteArrayToHexString(encryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            encryptedText = null;
            ivspec = null;
            skeySpec = null;
            cipher = null;
            text = null;
        }
        return s.toUpperCase();
    }


    public static String decryptAES(String key, String encryptedString) {
        SecretKeySpec skeySpec = null;
        IvParameterSpec ivspec = null;
        Cipher cipher = null;
        byte[] textDecrypted = null;

        try {
            byte[] b = hexStringToByteArray(encryptedString);
            skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
            ivspec = new IvParameterSpec(AES_IV.getBytes("UTF-8"));
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(2, skeySpec, ivspec);
            textDecrypted = cipher.doFinal(b);
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            skeySpec = null;
            ivspec = null;
            cipher = null;
        }

        return new String(textDecrypted);
    }

    public static String byteArrayToHexString(byte[] data) {
        StringBuffer buf = new StringBuffer();

        for (int i = 0; i != data.length; ++i) {
            int v = data[i] & 255;
            buf.append("0123456789abcdef".charAt(v >> 4));
            buf.append("0123456789abcdef".charAt(v & 15));
        }

        return buf.toString();
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }

        return data;
    }
}
